package cn.huiyunche.driver.datasync.schedule;

import cn.huiyunche.base.service.model.TmsOrder;
import cn.huiyunche.base.service.utils.DateUtils;
import cn.huiyunche.driver.service.FetchTmsOrder;
import cn.huiyunche.driver.service.OrderService;
import com.beust.jcommander.internal.Lists;
import org.apache.commons.collections4.CollectionUtils;
import org.joda.time.DateTime;
import org.quartz.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.Serializable;
import java.util.Date;
import java.util.List;

/**
 * 订单导入
 * Created by zhaoguixin on 2017/6/26.
 */
@PersistJobDataAfterExecution
@DisallowConcurrentExecution
public class ImportOrderSchedule implements Job, Serializable {

    private static final long serialVersionUID = 8831704998246107941L;
    private static final Logger LOGGER = LoggerFactory.getLogger(ImportOrderSchedule.class);

    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {

        LOGGER.info("ImportOrderSchedule.execute start : {}", new DateTime().toString(DateUtils.YYYY_MM_DD_HH_MM_SS_SSS));
        FetchTmsOrder fetchTmsOrder = QuartzClusterFactory.getFetchTmsOrder();
        OrderService orderService = QuartzClusterFactory.getOrderService();

        Date lastTime = fetchTmsOrder.fetchLastTimeSuccess();

        //得到待处理订单
        List<String> orderNos = fetchTmsOrder.fetchLastOrderNo(lastTime);

        if(CollectionUtils.isEmpty(orderNos)) {
            LOGGER.info("无最新订单");
            return;
        }

        //循环处理订单
        TmsOrder tmsOrder;
        List<TmsOrder> tmsOrders = Lists.newArrayList();
        for (String orderNo:orderNos) {
            tmsOrder = fetchTmsOrder.fetchTmsOrderByOrderNo(orderNo);
            if(null==tmsOrder){
                continue;
            }
            tmsOrders.add(tmsOrder);
            try {
                orderService.handleTmsOrders(tmsOrders);
            }catch (Exception e) {
                LOGGER.error("OrderServiceImpl.handleTmsOrders is error orderNo:{},e:{}.", orderNo,e);

            }
            tmsOrders.clear();
        }

        LOGGER.info("ImportOrderSchedule.execute end time : {}", new DateTime().toString(DateUtils.YYYY_MM_DD_HH_MM_SS_SSS));

    }
}
